function getQueryVariable (variable) {
  let params = getQueryStr()
  let result = 'no_jsessionid'
  if (params[variable]) {
    result = params[variable]
  }
  if (result === 'no_jsessionid') {
    result = getQueryString(variable)
  }
  return result
}

function getQueryStr (urls = '') {
  let url = urls || (window.location.href.split('#')[1] || window.location.href)
  url = decodeURIComponent(url)
  let result = {}
  let arr = url.split('?')
  let params = arr[1] && arr[1].split('&')
  if (!params) return result
  for (let i = 0; i < params.length; i++) {
    let item = params[i].split('=')
    item[0] = decodeURIComponent(item[0])
    item[1] = decodeURIComponent(item[1])
    result[item[0]] = item[1]
  }
  return result
}

function getQueryString (key) {
  var after = window.location.search
  if (after.indexOf('?') === -1) return null
  after = after.substring(1) || window.location.hash.split('?')[1]
  if (after) {
    var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
    var r = after.match(reg)
    if (r != null) {
      return decodeURIComponent(r[2])
    } else {
      return null
    }
  }
}

const TOKEN_PARAM_NAME = 'jsessionid'

export default {
  jsessionid: function () {
    return getQueryVariable(TOKEN_PARAM_NAME)
  },
  sessionName: TOKEN_PARAM_NAME,
  // 生成 router 的 query 部分
  routerQuery: function (session) {
    return {
      [TOKEN_PARAM_NAME]: session || this.jsessionid()
    }
  },
  // 生成 router 的 query 部分
  routerQueryString: function (session) {
    return TOKEN_PARAM_NAME + '=' + (session || this.jsessionid())
  }
}
